<template>
  <div class="wavesur-wrap">
    <div :id="wavesurferId"></div>
    <p v-show="!playShow && showNoUse" class="nouse-audio">
      录音正在生成，请尝试重新打开这条记录获取录音，若通话未产生通话内容则无法获取录音。
    </p>
    <div class="wave-detail-box" v-show="playShow">
      <i
        class="MC_iconfont"
        :class="isplay ? 'MC_icon-qiyong-kaishi' : 'MC_icon-qiyong-zanting'"
        @click="playOrPause"
      ></i>
      <a :href="srcUrl" target="_blank" download>
        <i class="MC_iconfont MC_icon-shangchuan-xiazai"></i>
      </a>
      <span class="audio-time">{{ timeStr }}</span>
    </div>
  </div>
</template>

<script lang="ts">
let clearInter: any
const timeNumber = 1000
import { defineComponent, reactive, onMounted, onDeactivated, onActivated, watch, toRefs } from 'vue'
import WaveSurfer from 'wavesurfer.js'
import { getCallTimeLength } from '@/common/utils/common'
export default defineComponent({
  name: 'waveSurfer',
  components: {},
  // ----------------生命周期-----------------------
  props: {
    srcUrl: {
      // 波纹的音频地址
      type: String,
      default: ''
    },
    wavesurferId: {
      // 波纹盒子的id,注意不能重复
      type: String,
      default: ''
    },
    isAutoPlay: {
      // 是否自动播放
      type: Boolean,
      default: false
    }
  },
  setup(props) {
    const STATE = reactive({
      showNoUse: true,
      wavesurferObj: {} as any,
      isplay: true,
      timeStr: '00:00:00/00:00:00',
      currentTime: 0,
      allTime: 0,
      isActivated: false,
      playShow: true
    })
    const getLastTime = (time1: any, time2: any) => {
      return getCallTimeLength(time1, false) + '/' + getCallTimeLength(time2, false)
    }
    const pauseAudio = () => {
      STATE.wavesurferObj.pause()
      STATE.isplay = true
    }
    const playOrPause = () => {
      STATE.wavesurferObj.playPause()
      STATE.isplay = !STATE.isplay
      if (STATE.isActivated) {
        // 组件再次激活时，重新激活定时器
        setInterValTimer()
      }
    }
    const closeDial = () => {
      const pane = document.getElementById(props.wavesurferId)
      if (pane) {
        pane.innerHTML = ''
      }
      if (STATE.wavesurferObj && STATE.wavesurferObj.container) {
        // 解决第一次加载没有实体，直接调用方法报错导致绘图失败
        STATE.wavesurferObj.destroy() // 删除事件、元素并断开WebAudio节点。
      }
    }
    const setInterValTimer = () => {
      // 启动定时器
      clearInter = setInterval(() => {
        STATE.currentTime = Math.round(STATE.wavesurferObj.getCurrentTime() || 0)
        STATE.timeStr = getLastTime(STATE.currentTime, STATE.allTime)
      }, timeNumber)
    }
    const changeMave = () => {
      if (props.srcUrl) {
        const pane = document.getElementById(props.wavesurferId)
        if (!props.wavesurferId || !pane) {
          return false
        }
        const option = {
          container: document.getElementById(props.wavesurferId),
          waveColor: '#878787',
          progressColor: '#008CEE',
          cursorColor: '#008CEE',
          splitChannels: true,
          hideScrollbar: true,
          maxCanvasWidth: 500,
          height: 60,
          barHeight: 1,
          // barWidth: 4, // 此配置是波纹柱状显示
          // barGap: 3, // 此配置是结合barWidth使用的，设置柱子间的间距
          pixelRatio: 1,
          backend: 'MediaElement'
        }
        STATE.wavesurferObj = new WaveSurfer(option)
        STATE.wavesurferObj.init()
        STATE.wavesurferObj.load(`${props.srcUrl}?random=${Math.random()}`)
        // 为啥要加Math.random? => 腾讯云的cos 跨域配置有问题，已配置*，但还是会有部分录音加载跨域，故暂时前台加上随机数，每次加载最新的，不缓存
        STATE.wavesurferObj.on('ready', () => {
          setInterValTimer() // 启动定时器
          const timer = STATE.wavesurferObj.getDuration()
          STATE.allTime = timer || 0
          STATE.playShow = true
          STATE.showNoUse = true
          STATE.isplay = true
          if (props.isAutoPlay) {
            // 是否自动播放
            STATE.wavesurferObj.play()
            STATE.isplay = false
          } else {
            STATE.wavesurferObj.pause()
            STATE.isplay = true
          }
        })
        STATE.wavesurferObj.on('error', () => {
          // 录音加载失败时，就销毁绘图 && 提示无效录音 && 隐藏播放按钮
          closeDial()
          STATE.playShow = false
          console.log('======加载录音失败哒======')
        })
        STATE.wavesurferObj.on('finish', () => {
          // 录音播放完毕时
          console.log('======录音播放完毕啦======')
          STATE.isplay = true
        })
      }
    }
    onMounted(() => {
      changeMave()
    })
    onActivated(() => {
      STATE.isActivated = true // 从别的模块再切回来，isActivated用于手动点击播放，再次启动定时器
    })
    onDeactivated(() => {
      // 组件暂停使用时，重置状态
      STATE.isplay = true
      STATE.isActivated = false
      clearInterval(clearInter) // 去别的模块，组件暂停使用时，去除定时器
    })
    watch(
      () => props.srcUrl,
      (url) => {
        console.log(url, 'change=====')
        setTimeout(() => {
          // 延时是因为盒子的id还没有
          closeDial() // 更换url的时候先清空原来的，再重新画波纹
          STATE.currentTime = 0
          STATE.allTime = 0
          clearInterval(clearInter) // 切换的时候先清除之前的定时器，否则会累加
          changeMave()
        }, 500)
      },
      { immediate: true }
    )
    return { playOrPause, ...toRefs(STATE) }
  }
})
</script>

<style lang="stylus" scoped>
.wavesur-wrap
  a
    text-decoration none
  .wave-detail-box
    margin-top 16px
    span
      display inline-block
      vertical-align text-top
      padding-left 18px
  .nouse-audio
    line-height 36px
  .audio-time
    width 110px
  .MC_iconfont
    font-size 20px
    color var(--mc-main-color)
  .MC_icon-shangchuan-xiazai
    margin-left 18px
</style>
